<?php
namespace Admin\Controller;
use Common\Controller\AdminbaseController;
use Common\Libiary\BaseApiHttp;
use Common\Libiary\BillHttp;
use Common\Libiary\ClientApiHttp;
use Common\Libiary\Uploadify;
class ActivitesController extends AdminbaseController{

	public function listActivite(){
		$ret = $this->_call_api('AppActivity.searchactivity',array('title'=>I('title',''),'page'=>I('p',1)));
		$count = $ret['total'];
		$activities = $ret['activities'];
		$page=$this->page($count,20);
		$page->setLinkWraper("li");
		$page->pageParam['title'] = I('title','');
		foreach($activities as $id=>$act){
			$activities[$id]['citynames'] = $this->_handle_city($act['cityIds'],false);
		}
		$this->assign('activites',$activities);
		$this->assign("pager",$page->show("default"));
		$this->display('listActivite');
	}

	public function addActivite(){
		$this->assign('citylist',$this->getCityList());
		if($_GET['debug']==2){
			var_dump($this->getCityList());
			exit();
		}
		$this->display('addActivite');
	}

	public function editActivite(){
		if(I('id')){
			$activity = $this->_call_api('AppActivity.getappactivitybyid',array('id'=>I('id')));
			$property = html_entity_decode($activity['property']);
			$property = json_decode($property ,true);
			$property = empty($property)?array():$property;
			$activity = array_merge($activity,$property);
			$activity['islogin'] = $activity['action'] == 5?1:0;
			$citys = $this->_handle_city($activity['citys']);
			// var_dump($activity);
			$this->assign('citys',$citys);
			$this->assign('activity',$activity);
			$this->assign('citylist',$this->getCityList());
			$this->display('editActivite');
		}else{
			$this->error('活动不存在');
		}
	}

	//保存数据
	public function saveActivite(){

		//保存活动
		$data = array();
		$req = I('');
		$data['title'] = $req['title'];
		$data['link']  = $req['link'];
		$data['id']    = $req['id'];
		$data['onlinetime'] = strtotime($req['onlineTime']);
		$data['offlinetime']= strtotime($req['offlineTime']);

		$imgInfo = $this->upload();

		if($imgInfo['smallImage']) $data['smallimage'] = $imgInfo['smallImage'];
		if($imgInfo['fullImage']) $data['fullimage']  = $imgInfo['fullImage'];

		$data['cityids'] = implode(',',$req['citys']);

		if(!empty($req['shareTitle']) && empty($req['islogin']) ){
			$data['action'] = 3;
		}elseif( !empty($req['shareTitle']) && !empty($req['islogin'])  ){
			$data['action'] = 5;
		}elseif(!empty($req['shopid']) && ($req['action'] == 1 || $req['action'] == 2)){
			$data['action'] = $req['action'];
		}elseif(($req['action'] == 6 || $req['action'] == 7)){
			$data['action'] = $req['action'];
		}else{
			$data['action'] = 3;
		}

		if($data['action'] == 2){
			$data['shopid'] = $req['manageShopId'];
		}elseif($data['action'] == 1){
			$data['shopid'] = $req['shopid'];
		}

		$property = array();
		if($data['action'] == 5 || $data['action']==3){
			$property['shareTitle'] = empty($req['shareTitle'])?$req['title']:$req['shareTitle'];
			$property['shareLink'] = empty($req['shareLink'])?$req['link']:$req['shareLink'];
			$property['shareDesc'] = $req['shareDesc'];
		}

		if($data['action'] == 2|| $data['action']==1){
			$property['shopid'] = $req['shopid'];
			$property['manageShopId'] = $req['manageShopId'];
			$property['shopName'] = $req['shopName'];
		}

		$data['property'] = json_encode($property);
		// if(!I('debug'))echo json_encode($data);exit();
		$ret = $this->_call_api('AppActivity.saveactivity',$data);
		if($ret)
			$this->success('保存成功');
		else
			$this->error('保存失败');

	}

	public function searchCity(){
		$search = I('search');
		$search = htmlentities($search);
		$db = M('cityTable');
		$map['name'] = array('like', "%$search%");
		$ret = $db->field('cityid,name')->where(" name like '%$search%'")->select();
		$this->_echo_json(0,$ret,'请求成功');
	}

	//处理状态
	public function handelStatus(){
		$req = I('');
		$data['id'] = $req['id'];
		$data['status'] = $req['status'];
		$res = $this->_call_api('AppActivity.changeappactivitystatus',$data);
		if($res){
			$this->success('更新成功');
		}else{
			$this->error('更新失败');
		}
	}


	private function upload(){
		$upload = new Uploadify();
		$imgMsg = array();
		foreach ($_FILES as $key=>$file){
		    if(!empty($file['name']) && !is_array($file['name'])) {

		        $info = $upload->uploadify($file);
		        if($info){ // 保存附件信息
		           $imgMsg[$key] = $info;
		        }
		    }elseif(!empty($file['name']) && is_array($file['name'])){
				foreach($file['name'] as $f_k =>$file_l){
					$file_info = array();
					$file_info['name'] = $file_l;
					$file_info['type'] = $file['type'][$f_k];
					$file_info['tmp_name'] = $file['tmp_name'][$f_k];
					$file_info['size'] = $file['size'][$f_k];
					$file_info['error'] = $file['error'][$f_k];
					$info = empty($file_l)?"":$upload->uploadify($file_info);
					$imgMsg[] = $info;
				}
			}
		}
		return $imgMsg;
	}

	private function _echo_json($errno,$data = array(),$msg=""){

		$info = array(
				'errno'=>$errno,
				'data'=>$data,
				'msg'=>$msg
			);
		echo json_encode($info);
		exit();
	}


	private function _handle_city($cityids,$isArr = 1){
		$citylist = $this->getCityList();
		$citys = array();
		foreach($cityids as $cityid){
			if($cityid['cityid']==0){
				$citys = array('cityid'=>0,'name'=>'所有城市');
				break;
			}
			foreach($citylist as $city){
				if($cityid['cityid'] == $city['cityId']){
					$citys[] = array('cityid'=>$cityid['cityid'],'name'=>$city['cityName']);
					break;
				}
			}
		}
		if(!$isArr){
			$citynames =array();
			foreach($citys as $city){
				$citynames[] = $city['name'];
			}
			return implode(',',$citynames);
		}
		return $citys;
	}

	private function getCityList(){
		if(isset($_SESSION['allcity']) && $_SESSION['allcity']){
			return $_SESSION['allcity'];
		}
		$baseApi = new BaseApiHttp();
		$params = $baseApi->build_params();
		$url = 'http://www.mwee.cn/basic/api/app.getcitylist';
        $ret = $baseApi->http( $url, 'POST', $params );
        $ret = json_decode($ret,true);
        $_SESSION['allcity']=$ret['data'];
        return $ret['data'];
	}

	private function _call_api($api,$data){
		$clientApi = new ClientApiHttp();
		$ret = $clientApi->https_request($api, $data);
		if(!$ret || $ret['errno'] != 0){
			return false;
		}
		return $ret['data'];

	}

	public function searchShop(){
		$data['kw'] = I('shopName');
		$data['cityid'] = I('cityId',0);
		$ret = $this->_call_api('shop.getlist',$data);
		echo json_encode($ret);
	}


	public function editHotShop(){
		$citys = $this->getCityList();
		$this->assign('citylist',$citys);
		$this->display('editHotShop');
	}

	public function saveHotShop(){
		if(!empty($_POST)){
			$data = $_POST;
			$data['files']  = $_FILES;
			$data['upfiles']  = $this->upload();
			$hotShopData = array();
			$hotShopData['cityid'] = $data['cityid'];
			$orders = $data['orders'];
			asort($orders,SORT_NUMERIC);
			$orders = implode(',',$data['orders']) == implode(',',$orders)?$data['orders']:$orders;
			$shopDatas = array();
			foreach($orders as $key=>$val){
				$shopData['branchName'] = $data['branchNames'][$key];
				$shopData['branchId'] = $data['branchIds'][$key];
				$shopData['branchIconUrl'] = empty($data['upfiles'][$key])?$data['branchUrls'][$key]:$data['upfiles'][$key];
				array_push($shopDatas,$shopData);
			}
			$hotShopData['content'] = json_encode($shopDatas);
			$bill = new BillHttp();
			$ret = $bill->CurlHttp('ad.updatehotshop',$hotShopData);
			$ret = json_decode($ret,true);
			if($ret['errno'] == 0){
				$this->success('更新成功');
			}else{
				$this->error('更新失败');
			}
		}
	}

	public function searchHotShops(){
		$data['cityid'] = I('cityid',258);
		$bill = new BillHttp();
		$data = $bill->CurlHttp('ad.gethotshop',$data);
		echo $data;exit();
	}

	public function deleteHotShops(){
		$data['cityid'] = I('cityid');
		$bill = new BillHttp();
		echo $bill->CurlHttp('ad.delhotshop',$data);
		exit();
	}

	public function listQueueBanner(){
        $ret = $this->_call_api('AppActivity.getqueuebanners',array('page'=>I('p',1)));
        $count = $ret['total'];
        $list = $ret['list'];
        $page=$this->page($count,20);
        $page->setLinkWraper("li");
        foreach($list as $id=>$banner){
            $property = json_decode(html_entity_decode($banner['property']),true);
            $list[$id]['shareDesc'] = $property['shareDesc'];
            $list[$id]['shareTitle'] = $property['shareTitle'];
            $list[$id]['title'] = $property['title'];
            $list[$id]['link'] = $property['link'];
            $list[$id]['shopName'] = $property['shopName'];
            $list[$id]['image'] = $property['image'];
        }
        $this->assign('banners',$list);
        $this->assign("pager",$page->show("default"));
        $this->display();
    }

    public function QueueBanner(){
        if(!empty(I('id'))){
            $banner = $this->_call_api('AppActivity.getqueuebannerbyid',array('id'=>I('id')));
            $property = json_decode(html_entity_decode($banner['property']),true);
            $banner['shareDesc'] = $property['shareDesc'];
            $banner['shareTitle'] = $property['shareTitle'];
            $banner['title'] = $property['title'];
            $banner['link'] = $property['link'];
            $banner['shopName'] = $property['shopName'];
            $banner['image'] = $property['image'];
            $this->assign('banner',$banner);
        }
        $this->display();
    }


    public function saveQueueBanner(){
        $property['shareDesc'] = I('shareDesc','');
        $property['shareTitle'] = I('shareTitle','');
        $property['link'] = I('link','');
        $property['shopName'] = I('shopName','');
        $property['title'] = I('title','');
        $image = $this->upload();
        $property['image'] = isset($image['image'])?$image['image']:I('image','');
        $banner['property'] = json_encode($property);

        $banner['shopid'] = I('shopid','');
        $banner['m_shopid'] = I('manageShopId','');
        $banner['type'] = I('type',0);
        if(I('id')) $banner['id'] = I('id');
        $banner['status'] = I('status',0);

        $ret = $this->_call_api('AppActivity.savequeuebannner',$banner);
        if($ret){
            $this->success('保存成功');
        }else{
            $this->error('保存失败');
        }
    }

    public function changeQueueBannerStatus(){
        $banner['id'] = I('id');
        $banner['status'] = I('status',0);
        $ret = $this->_call_api('AppActivity.changequeuebannnerstatus',$banner);
        if($ret){
            $this->success('保存成功');
        }else{
            $this->error('保存失败');
        }

    }
}